<template>
  <el-dialog
    v-model="dialogVisible"
    title="标签管理"
    width="800px"
    class="cyber-dialog tag-management-dialog"
    :before-close="handleClose"
    destroy-on-close
    :close-on-click-modal="false"
    :close-on-press-escape="true"
  >
    <div class="dialog-content">
      <!-- 添加新标签 -->
      <div class="cyber-card add-section">
        <h3 class="section-title cyber-text-gradient">
          <el-icon><Plus /></el-icon>
          添加新标签
        </h3>
        <div class="add-form">
          <el-input
            v-model="newTagName"
            placeholder="请输入标签名称"
            class="cyber-input tag-input"
            @keyup.enter="addTag"
            show-word-limit
          >
            <template #prefix>
              <el-icon><Collection /></el-icon>
            </template>
          </el-input>
          <div class="color-input-group">
            <el-input
              v-model="newTagColor"
              placeholder="标签颜色"
              class="cyber-input color-input"
              @keyup.enter="addTag"
            >
              <template #prefix>
                <el-icon><Brush /></el-icon>
              </template>
              <template #suffix>
                <div 
                  class="color-preview" 
                  :style="{ backgroundColor: newTagColor || '#32ec8a' }"
                ></div>
              </template>
            </el-input>
            <el-color-picker
              v-model="newTagColor"
              size="default"
              :predefine="['#32ec8a','#409EFF','#ff6b6b','#ffd93d','#6bcf7f','#a78bfa','#f472b6','#22d3ee']"
              color-format="hex"
              class="color-picker-btn"
            />
          </div>
          <el-button
            type="primary"
            @click="addTag"
            class="cyber-btn add-btn"
            :disabled="!canAddTag"
            :loading="loading"
          >
            <el-icon><Plus /></el-icon>
            添加标签
          </el-button>
        </div>
      </div>

      <!-- 标签列表 -->
      <div class="cyber-card tags-section">
        <div class="section-header">
          <h3 class="section-title cyber-text-gradient">
            <el-icon><Collection /></el-icon>
            现有标签
          </h3>
          <span class="tag-count-badge">{{ tags.length }}</span>
        </div>
        
        <div v-if="loading" class="loading-container">
          <el-icon class="loading-icon"><Loading /></el-icon>
          <span>加载中...</span>
        </div>
        
        <div v-else-if="isEmpty" class="empty-container">
          <el-icon class="empty-icon"><Collection /></el-icon>
          <p>暂无标签，请先添加</p>
        </div>
        
        <div v-else class="tags-container">
          <TransitionGroup name="tag-list" tag="div">
            <div
              v-for="tag in sortedTags"
              :key="tag.id"
              class="cyber-card tag-item"
              :style="{ 
                '--tag-color': tag.color || '#32ec8a',
                '--tag-color-rgb': hexToRgb(tag.color || '#32ec8a')
              }"
            >
              <div class="tag-info">
                <div
                  class="tag-color-indicator"
                  :style="{ backgroundColor: tag.color || '#32ec8a' }"
                ></div>
                <div class="tag-details">
                  <span class="tag-name">{{ tag.name }}</span>
                  <span class="tag-meta">{{ tag.count || 0 }} 个智能体</span>
                </div>
              </div>
              <div class="tag-actions">
                <el-button
                  size="small"
                  @click="handleEditTag(tag)"
                  class="cyber-btn cyber-btn-edit"
                  :icon="Edit"
                  circle
                />
                <el-button
                  size="small"
                  @click="handleDeleteTag(tag)"
                  class="cyber-btn cyber-btn-delete"
                  :icon="Delete"
                  circle
                />
              </div>
            </div>
          </TransitionGroup>
        </div>
      </div>
    </div>

    <!-- 编辑标签弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑标签"
      width="400px"
      class="cyber-dialog edit-tag-dialog"
      append-to-body
      destroy-on-close
    >
      <div class="edit-form">
        <el-form :model="editingTag" label-width="80px" class="cyber-form">
          <el-form-item label="标签名称">
            <el-input 
              v-model="editingTag.name" 
              placeholder="请输入标签名称"
              class="cyber-input"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="标签颜色">
            <div class="color-input-group">
              <el-input
                v-model="editingTag.color"
                placeholder="请输入颜色值"
                class="cyber-input"
              />
              <el-color-picker
                v-model="editingTag.color"
                size="small"
                :predefine="['#32ec8a','#409EFF','#ff6b6b','#ffd93d','#6bcf7f','#a78bfa','#f472b6','#22d3ee']"
                color-format="hex"
              />
              <div 
                class="color-preview-large"
                :style="{ backgroundColor: editingTag.color || '#32ec8a' }"
              ></div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelEdit" class="cyber-btn">取消</el-button>
          <el-button type="primary" @click="saveEdit" class="cyber-btn cyber-btn-primary">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Collection, Brush, Loading } from '@element-plus/icons-vue'
import { useTags } from '@/composables/useTags'

// 使用标签管理 composable
const {
  tags,
  loading,
  error,
  hasError,
  isEmpty,
  hasMore,
  fetchTags,
  fetchTagById,
  createTag,
  updateTag,
  deleteTag,
  clearError
} = useTags()

// 组件属性
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

// 组件事件
const emit = defineEmits(['update:visible', 'tag-updated'])

// 响应式数据
const newTagName = ref('')
const newTagColor = ref('#409EFF')
const editingTag = ref({
  id: '',
  name: '',
  color: '',
  description: '',
  count: 0,
  createdAt: '',
  updatedAt: ''
})
const editDialogVisible = ref(false)

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const canAddTag = computed(() => {
  return newTagName.value.trim() && !loading.value
})

const sortedTags = computed(() => {
  return [...tags.value].sort((a, b) => a.name.localeCompare(b.name))
})

// 生命周期钩子
onMounted(() => {
  if (props.visible) {
    loadTags()
  }
})

// 监听对话框显示状态
watch(dialogVisible, (visible) => {
  if (visible) {
    loadTags()
    clearError()
  }
})

/**
 * 加载标签列表
 */
async function loadTags() {
  try {
    await fetchTags()
    if (hasError.value) {
      ElMessage.error(error.value || '加载标签失败')
    }
  } catch (error) {
    console.error('加载标签失败:', error)
    ElMessage.error('加载标签失败')
  }
}

/**
 * 检查标签名称是否已存在
 */
function isNameExists(name, excludeId = null) {
  return tags.value.some(tag => 
    tag.name === name && tag.id !== excludeId
  )
}

/**
 * 将十六进制颜色转换为RGB值
 */
function hexToRgb(hex) {
  // 移除 # 符号
  const cleanHex = hex.replace('#', '')
  
  // 解析RGB值
  const r = parseInt(cleanHex.substr(0, 2), 16)
  const g = parseInt(cleanHex.substr(2, 2), 16)
  const b = parseInt(cleanHex.substr(4, 2), 16)
  
  return `${r}, ${g}, ${b}`
}



/**
 * 添加标签
 */
async function addTag() {
  const trimmedName = newTagName.value.trim()
  
  if (!trimmedName) {
    ElMessage.warning('请输入标签名称')
    return
  }
  
  if (isNameExists(trimmedName)) {
    ElMessage.warning('标签名称已存在')
    return
  }

  try {
    const tagData = {
      name: trimmedName,
      color: newTagColor.value.trim() || '#32ec8a',
      description: '',
      isActive: true,
      sortOrder: tags.value.length + 1
    }

    const { success, error } = await createTag(tagData)
    
    if (success) {
      // 重置表单
      newTagName.value = ''
      newTagColor.value = ''
        
      ElMessage.success('标签添加成功')
      emit('tag-updated')
    } else if (error) {
      ElMessage.error(error)
    }
  } catch (error) {
    console.error('添加标签失败:', error)
    ElMessage.error('添加标签失败')
  }
}

/**
 * 编辑标签
 */
function handleEditTag(tag) {
  editingTag.value = { ...tag }
  editDialogVisible.value = true
}

/**
 * 保存编辑
 */
async function saveEdit() {
  const trimmedName = editingTag.value.name.trim()
  
  if (!trimmedName) {
    ElMessage.warning('请输入标签名称')
    return
  }
  
  if (isNameExists(trimmedName, editingTag.value.id)) {
    ElMessage.warning('标签名称已存在')
    return
  }

  try {
    const updateData = {
      name: trimmedName,
      color: editingTag.value.color || '#32ec8a',
      description: editingTag.value.description || ''
    }

    const { success, error } = await updateTag(editingTag.value.id, updateData)
    
    if (success) {
      editDialogVisible.value = false
      ElMessage.success('标签更新成功')
      emit('tag-updated')
    } else if (error) {
      ElMessage.error(error)
    }
  } catch (error) {
    console.error('更新标签失败:', error)
    ElMessage.error('更新标签失败')
  }
}

/**
 * 删除标签
 */
async function handleDeleteTag(tag) {
  try {
    await ElMessageBox.confirm(
      `确定要删除标签 "${tag.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const { success, error } = await deleteTag(tag.id)
    
    if (success) {
      ElMessage.success('标签删除成功')
      emit('tag-updated')
    } else if (error) {
      ElMessage.error(error)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除标签失败:', error)
      ElMessage.error('删除标签失败')
    }
  }
}

/**
 * 取消编辑
 */
function cancelEdit() {
  editDialogVisible.value = false
  editingTag.value = {
    id: '',
    name: '',
    color: '',
    description: '',
    count: 0,
    createdAt: '',
    updatedAt: ''
  }
}

/**
 * 关闭对话框
 */
function handleClose() {
  dialogVisible.value = false
}

</script>

<style lang="scss" scoped>
// Element Plus 组件样式已由 global.scss 统一管理
// 这里只保留组件特有的业务样式

// 内容布局
.dialog-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

// 组件特有样式
.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 1rem;
  font-weight: 600;
  margin: 0 0 10px 0;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 0px;
}

.tag-count-badge {
  padding: 4px 12px;
  border-radius: 5px;
  font-size: 0.875rem;
  font-weight: 600;
}

// 表单样式
.add-form {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.tag-input {
  flex: 1;
}

.color-input-group {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.color-input {
  flex: 1;
  min-width: 120px;
}

.color-picker-btn {
  flex-shrink: 0;
}

.color-preview {
  width: 16px;
  height: 16px;
  border-radius: 5px;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.color-preview-large {
  width: 32px;
  height: 32px;
  border-radius: 5px;
  border: 2px solid rgba(50, 236, 138, 0.3);
  margin-left: 8px;
}

// 输入框样式（组件特有样式）
.cyber-input {
  // 组件特有的输入框样式在这里定义
}

// 按钮样式（组件特有样式）
.cyber-btn {
  &.add-btn {
    &:disabled {
      background: rgba(50, 50, 50, 0.5) !important;
      color: rgba(255, 255, 255, 0.6) !important;
      border-color: rgba(255, 255, 255, 0.1) !important;
    }
  }
}

// 标签列表 - 重新设计为整齐有序的网格布局
.tags-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
  gap: 20px;
  max-height: 450px;
  overflow-y: auto;
  padding: 0px 8px;
  align-items: start;
  
  // 确保网格项目对齐
  justify-items: stretch;
  align-content: start;

  &::-webkit-scrollbar {
    width: 8px;
  }

  &::-webkit-scrollbar-track {
    background: rgba(255, 255, 255, 0.05);
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background: linear-gradient(45deg, #32ec8a, #22d3ee);
    border-radius: 4px;
    
    &:hover {
      background: linear-gradient(45deg, #22d3ee, #32ec8a);
    }
  }
}

// 标签项 - 优化布局和视觉效果
.tag-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  margin: 10px 0;
  min-height: 72px;
  border-radius: 8px;
  position: relative;
  overflow: hidden;
  
  // 添加渐变背景效果
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, 
      rgba(var(--tag-color-rgb, 50, 236, 138), 0.05) 0%,
      rgba(var(--tag-color-rgb, 50, 236, 138), 0.02) 100%);
    pointer-events: none;
  }
  
  
  // 过渡动画
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.tag-info {
  display: flex;
  align-items: center;
  gap: 16px;
  flex: 1;
  position: relative;
  z-index: 1;
}

.tag-color-indicator {
  width: 16px;
  height: 16px;
  border-radius: 8px;
  box-shadow: 0 0 12px rgba(var(--tag-color-rgb, 50, 236, 138), 0.6),
              0 0 24px rgba(var(--tag-color-rgb, 50, 236, 138), 0.3);
  border: 2px solid rgba(255, 255, 255, 0.1);
  flex-shrink: 0;
}

.tag-details {
  display: flex;
  flex-direction: column;
  gap: 6px;
  flex: 1;
  min-width: 0; // 防止文本溢出
}

.tag-name {
  font-weight: 600;
  font-size: 1rem;
  line-height: 1.4;
  color: rgba(255, 255, 255, 0.95);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tag-meta {
  font-size: 0.875rem;
  line-height: 1.3;
  color: rgba(255, 255, 255, 0.7);
  font-weight: 500;
}

.tag-actions {
  display: flex;
  gap: 10px;
  align-items: center;
  position: relative;
  z-index: 1;
  flex-shrink: 0;
  
  .cyber-btn {
    width: 36px;
    height: 36px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
    
    &.cyber-btn-edit {
      background: rgba(64, 158, 255, 0.1);
      border: 1px solid rgba(64, 158, 255, 0.3);
      color: #409EFF;
      
      &:hover {
        background: rgba(64, 158, 255, 0.2);
        border-color: rgba(64, 158, 255, 0.5);
        transform: scale(1.05);
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
      }
    }
    
    &.cyber-btn-delete {
      background: rgba(255, 107, 107, 0.1);
      border: 1px solid rgba(255, 107, 107, 0.3);
      color: #ff6b6b;
      
      &:hover {
        background: rgba(255, 107, 107, 0.2);
        border-color: rgba(255, 107, 107, 0.5);
        transform: scale(1.05);
        box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3);
      }
    }
  }
}

// 状态容器
.loading-container,
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 24px;
}

.loading-icon {
  font-size: 2rem;
  color: #32ec8a;
  animation: spin 1s linear infinite;
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 16px;
}

// 表单样式（组件特有样式）
.cyber-form {
  // 组件特有的表单样式在这里定义
}

// 动画
@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.tag-list-enter-active,
.tag-list-leave-active {
  transition: all 0.3s ease;
}

.tag-list-enter-from {
  opacity: 0;
  transform: translateX(-30px);
}

.tag-list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

.tag-list-move {
  transition: transform 0.3s ease;
}

// 标签样式（组件特有样式）
.cyber-tag {
  background: rgba(50, 236, 138, 0.15) !important;
  color: #32ec8a !important;
  border: 1px solid rgba(50, 236, 138, 0.3) !important;
  border-radius: 5px !important;
  padding: 6px 12px !important;
  font-size: 0.85rem !important;
  font-weight: 500 !important;
  display: inline-flex !important;
  align-items: center !important;
  gap: 6px !important;
  margin: 4px !important;
  transition: all 0.3s ease !important;
  cursor: pointer !important;

  .close-btn {
    color: rgba(50, 236, 138, 0.7) !important;
    font-size: 0.75rem !important;
    cursor: pointer !important;
    transition: color 0.2s ease !important;
  }
}

// Element Plus 组件样式现在由 global.scss 统一管理

// 响应式设计 - 优化不同屏幕尺寸下的布局
@media (max-width: 768px) {
  // Element Plus 对话框样式由 global.scss 统一管理
  
  .add-form {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .color-input {
    width: 100%;
  }
  
  .tags-container {
    grid-template-columns: 1fr;
    gap: 16px;
    padding: 4px;
  }
  
  .tag-item {
    padding: 14px 16px;
    min-height: 64px;
    
    .tag-info {
      gap: 14px;
    }
    
    .tag-actions {
      gap: 8px;
      
      .cyber-btn {
        width: 32px;
        height: 32px;
      }
    }
  }
  
  .cyber-card {
    padding: 16px;
  }
}

@media (max-width: 480px) {
  // Element Plus 对话框样式由 global.scss 统一管理
  
  .section-title {
    font-size: 1rem;
  }
  
  .tags-container {
    max-height: 350px;
  }
  
  .tag-item {
    padding: 12px 14px;
    min-height: 56px;
    border-left-width: 3px;
    
    .tag-info {
      gap: 12px;
    }
    
    .tag-color-indicator {
      width: 14px;
      height: 14px;
    }
    
    .tag-name {
      font-size: 0.9rem;
    }
    
    .tag-meta {
      font-size: 0.8rem;
    }
    
    .tag-actions {
      .cyber-btn {
        width: 30px;
        height: 30px;
        
        .el-icon {
          font-size: 14px;
        }
      }
    }
  }
}
</style>